package com.miaostars.apakey.events;

import com.miaostars.apakey.Apakey;
import com.miaostars.apakey.checks.MovementChecks;
import com.miaostars.apakey.checks.SpeedChecks;
import com.miaostars.apakey.utils.AlertManager;
import com.miaostars.apakey.utils.PlayerData;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerToggleFlightEvent;
import org.bukkit.util.Vector;

public class MovementListener implements Listener {
    
    private final Apakey plugin;
    private final MovementChecks movementChecks;
    private final SpeedChecks speedChecks;
    private final AlertManager alertManager;
    
    public MovementListener(Apakey plugin) {
        this.plugin = plugin;
        this.movementChecks = new MovementChecks(plugin);
        this.speedChecks = new SpeedChecks(plugin);
        this.alertManager = plugin.getAlertManager();
    }
    
    @EventHandler
    public void onMove(PlayerMoveEvent event) {
        Player player = event.getPlayer();
        PlayerData data = PlayerData.get(player);
        
        // Update player data
        data.setLastLocation(event.getFrom().toVector());
        data.setLastGroundTime(System.currentTimeMillis());
        
        // Check for fly hacks
        if (movementChecks.checkFly(player, data)) {
            alertManager.alert(player, "Fly", "A");
            event.setTo(event.getFrom());
            return;
        }
        
        // Check for no fall hacks
        if (movementChecks.checkNoFall(player, data)) {
            alertManager.alert(player, "NoFall", "A");
            event.setTo(event.getFrom());
            return;
        }
        
        // Check for high jump hacks
        if (movementChecks.checkHighJump(player, data)) {
            alertManager.alert(player, "HighJump", "A");
            event.setTo(event.getFrom());
            return;
        }
        
        // Check for speed hacks
        if (speedChecks.checkSpeed(player, data, event.getFrom().toVector(), event.getTo().toVector())) {
            alertManager.alert(player, "Speed", "A");
            event.setTo(event.getFrom());
            return;
        }
    }
    
    @EventHandler
    public void onToggleFlight(PlayerToggleFlightEvent event) {
        Player player = event.getPlayer();
        PlayerData data = PlayerData.get(player);
        
        if (!player.getAllowFlight() && event.isFlying()) {
            data.incrementFlyViolations();
            
            if (data.getFlyViolations() > plugin.getConfigManager().getConfig().getInt("checks.fly.max-violations")) {
                alertManager.alert(player, "Fly", "B");
                event.setCancelled(true);
            }
        }
    }
}
